package com.shenmazg6.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shenmazg6.pojo.TbRoom;
import com.shenmazg6.service.TbRoomService;
import com.shenmazg6.mapper.TbRoomMapper;
import com.shenmazg6.utils.CopyBeanUtils;
import com.shenmazg6.utils.IdWorker;
import com.shenmazg6.utils.ResultResponse;
import com.shenmazg6.utils.TxLiveUtils;
import com.shenmazg6.vo.IdVo;
import com.shenmazg6.vo.PageInfoVo;
import com.shenmazg6.vo.RoomInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author Think
* @description 针对表【tb_room(直播房间表)】的数据库操作Service实现
* @createDate 2022-12-22 15:45:15
*/
@Service
public class TbRoomServiceImpl extends ServiceImpl<TbRoomMapper, TbRoom>
    implements TbRoomService{

    @Override
    public ResultResponse add(RoomInfoVo roomInfoVo) {
        //--1 复制属性
        TbRoom tbRoom = new TbRoom();
        CopyBeanUtils.copy(roomInfoVo, tbRoom);

        //--2 生成推流地址
        tbRoom.setRoomNo(""+ IdWorker.getId());
        String pushUrl = TxLiveUtils.makePushUrl(tbRoom.getRoomNo(), roomInfoVo.getCloseTime());
        tbRoom.setPushUrl(pushUrl);

        //--3 生成播放地址
        String playUrl = TxLiveUtils.makePlayUrl(tbRoom.getRoomNo());
        tbRoom.setPlayUrl(playUrl);

        //--3 写入数据库
        tbRoom.setCoverUrl("https://upload.shenmazong.com/upload/955bb2ca-b4d6-4ab5-8e1e-69c35f277af7.png");
        save(tbRoom);

        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse listByPage(PageInfoVo pageInfoVo) {
        // 得到列表数据
        Page<TbRoom> p = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        Page<TbRoom> tbRoomPage = page(p, new QueryWrapper<TbRoom>().lambda().orderByDesc(TbRoom::getRoomId));

        // 数据转换
        Page<RoomInfoVo> infoVoPage = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        BeanUtils.copyProperties(tbRoomPage, infoVoPage);

        List<RoomInfoVo> collect = tbRoomPage.getRecords().stream().map(item -> {
            RoomInfoVo roomInfoVo = new RoomInfoVo();
            BeanUtils.copyProperties(item, roomInfoVo);
            return roomInfoVo;
        }).collect(Collectors.toList());

        infoVoPage.setRecords(collect);

        return ResultResponse.SUCCESS(infoVoPage);
    }

    @Override
    public ResultResponse getRoomById(IdVo idVo) {

        TbRoom tbRoom = getById(idVo.getId());
        if(tbRoom == null) {
            return ResultResponse.FAILED(404, "房间不存在");
        }

        return ResultResponse.SUCCESS(tbRoom);
    }


}




